use calamine::{open_workbook, Reader, Xlsx};
use std::path::PathBuf;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct ExcelData {
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
}

#[tauri::command]
pub async fn parse_excel(file_path: PathBuf) -> Result<ExcelData, String> {
    let mut workbook: Xlsx<_> = open_workbook(&file_path)
        .map_err(|e| format!("打开文件失败: {}", e))?;

    let range = workbook.worksheet_range_at(0)
        .ok_or_else(|| "找不到工作表".to_string())?
        .map_err(|e| format!("读取工作表失败: {}", e))?;

    let mut headers = Vec::new();
    let mut rows = Vec::new();

    // 处理表头
    if let Some(first_row) = range.rows().next() {
        for cell in first_row {
            headers.push(cell.to_string());
        }
    }

    // 处理数据行（跳过表头）
    for row in range.rows().skip(1) {
        let mut row_data = Vec::new();
        for cell in row {
            row_data.push(cell.to_string());
        }
        rows.push(row_data);
    }

    Ok(ExcelData { headers, rows })
}
